<template>
    <section>
        <!--工具条-->
        <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
            <el-form :inline="true" :model="filters">
                <el-form-item>
                    <el-input v-model="filters.title" placeholder="片名" clearable></el-input>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" v-on:click="getVideoList">查询</el-button>
                </el-form-item>

            </el-form>
        </el-col>

        <!--列表-->
        <el-table :data="videoList" stripe highlight-current-row v-loading="listLoading"
                  :row-class-name="tableRowClassName"
                  style="width: 100%;">
            <el-table-column type="selection" width="55"/>

            <el-table-column prop="title" label="片名" width="120"/>
            <el-table-column prop="score" label="评分" width="80" />
            <el-table-column label="封面" width="120">
                <template slot-scope="scope">
                    <el-image
                        style="width: 100px; "
                        :src="scope.row.cover" >
                    </el-image>
                </template>
            </el-table-column>
            <!--<el-table-column prop="video" label="视频" />-->
<!--            <el-table-column prop="type" label="标签" />-->
            <el-table-column prop="description" label="描述" />
            <el-table-column prop="createTime" label="创建时间" width="140" :formatter="formatDate" sortable />

            <el-table-column label="操作" width="160" fixed="right" style="padding-right: 2px">
                <template slot-scope="scope">
                    <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
                    <el-button type="danger" size="mini" @click="handleDel(scope.$index, scope.row)">下架</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!--工具条-->
        <el-col :span="24" class="toolbar">
            <el-button type="danger" v-on:click="batchRemove" :disabled="this.sels.length===0">批量下架</el-button>
            <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="currPage"
                :page-sizes="[10, 20, 50]"
                :page-size="10"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"
                style="float:right;">
            </el-pagination>
        </el-col>

        <!--编辑界面-->
        <el-dialog title="编辑" :visible.sync="editFormVisible" :close-on-click-modal="false">
            <el-form :model="editForm" label-width="80px" ref="editForm">
                <el-form-item label="片名" prop="name">
                    <el-input v-model="editForm.title" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="评分">
                    <el-input v-model="editForm.score" auto-complete="off"></el-input>
                </el-form-item>
                <el-form-item label="封面">
                    <el-image
                        style="width: 300px; "
                        :src="editForm.cover" >
                    </el-image>
                </el-form-item>
                <el-form-item label="描述">
                    <el-input v-model="editForm.description"></el-input>
                </el-form-item>
                <el-form-item label="标签" prop="type">
                    <el-input v-model="editForm.type"/>
                </el-form-item>
                <el-form-item label="视频">
                    <div class='demo'>
                        <video-player class="video-player vjs-custom-skin"
                                      ref="videoPlayer"
                                      :playsinline="true"
                                      @pause="pausePlay($event)"
                                      :options="playerOptions">
                        </video-player>
                    </div>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
<!--                editFormVisible = false -->
                <el-button @click.native="cancleSubmit">取消</el-button>
                <el-button type="primary" @click.native="editSubmit" :loading="editLoading">提交</el-button>
            </div>
        </el-dialog>

    </section>
</template>

<script>
    import util from '../../common/utils'
    import {movieList,movieDetail} from '../../api/system/app';
    import {getTime} from '../../api/commonUtil';

    export default {
        data() {
            return {
                playerOptions: {
                    //播放速度
                    playbackRates: [0.5, 1.0, 1.5, 2.0],
                    //如果true,浏览器准备好时开始回放。
                    autoplay: false,
                    // 默认情况下将会消除任何音频。
                    muted: false,
                    // 导致视频一结束就重新开始。
                    loop: false,
                    // 建议浏览器在<video>加载元素后是否应该开始下载视频数据。auto浏览器选择最佳行为,立即开始加载视频（如果浏览器支持）
                    preload: 'auto',
                    language: 'zh-CN',
                    // 将播放器置于流畅模式，并在计算播放器的动态大小时使用该值。值应该代表一个比例 - 用冒号分隔的两个数字（例如"16:9"或"4:3"）
                    aspectRatio: '16:9',
                    // 当true时，Video.js player将拥有流体大小。换句话说，它将按比例缩放以适应其容器。
                    fluid: true,
                    sources: [{
                        //类型
                        type: "video/mp4",
                        //url地址
                        src: ''
                    }],
                    //你的封面地址
                    poster: '',
                    //允许覆盖Video.js无法播放媒体源时显示的默认信息。
                    notSupportedMessage: '此视频暂无法播放，请稍后再试',
                    controlBar: {
                        timeDivider: true,
                        durationDisplay: true,
                        remainingTimeDisplay: false,
                        //全屏按钮
                        fullscreenToggle: true
                    },
                },
                filters: {
                    title: '',
                },
                videoList: [],
                total: 0,
                currPage: 1,
                pageSize: 10,
                listLoading: false,
                sels: [],//列表选中列
                editFormVisible: false,//编辑界面是否显示
                editLoading: false,
                //编辑界面数据
                editForm: {
                    title: '',
                    score: -1,
                    cover: '',
                    description: '',
                    type: '',
                    video: ''
                },
                addFormVisible: false,//新增界面是否显示
                addLoading: false,
                formLabelWidth: '80px',
            }
        },
        methods: {
            // 隔行换色
            tableRowClassName({row, rowIndex}) {
                if (rowIndex === 1) {
                    return 'warning-row';
                } else if (rowIndex === 3) {
                    return 'success-row';
                }
                return '';
            },

            formatDate: function (row, column, cellValue, index) {
                const daterc = row[column.property]
                return daterc == null ? 'null' : getTime(daterc);
            },
            // 切换pageSize
            handleSizeChange(val) {
                this.pageSize = val;
                this.getVideoList();
            },
            // 换页
            handleCurrentChange(val) {
                this.currPage = val;
                this.getVideoList();
            },

            //获取视频列表
            getVideoList() {
                let params = {
                    title: this.filters ? this.filters.title : '',
                    currentPage: this.currPage,
                    pageSize: this.pageSize == null ? 10 : this.pageSize,
                };
                this.listLoading = true;
                movieList(params).then((res) => {
                    if (res != undefined&&res.status ) {
                        this.$message({
                            message: '加载成功',
                            type: 'success'
                        });
                        if (res.data !== undefined && res.data !== null) {
                            this.total = parseInt(res.data.totalCount);
                            this.currPage = parseInt(res.data.currPage);
                            this.videoList = res.data.list;
                        } else {
                            this.total = 0;
                            this.videoList = [];
                        }
                    } else {
                        this.listLoading = false;
                        this.$message({
                            message: '加载失败',
                            type: 'error'
                        });
                    }
                    this.listLoading = false;
                });
            },
            //下架
            handleDel: function (index, row) {
                this.$confirm('确认删除该记录吗?', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;
                    debugger;
                    var userId = {
                        "userId": row.userId
                    };
                    removeUser(userId).then((res) => {
                        this.listLoading = false;
                        if (res.status) {
                            this.$message({
                                message: '删除成功',
                                type: 'success'
                            });
                        } else {
                            this.$message({
                                message: '删除失败',
                                type: 'warning'
                            });
                        }
                        this.getVideoList();
                    });
                }).catch(() => {
                    this.listLoading = false;
                    this.$message({
                        message: '删除失败',
                        type: 'warning'
                    });
                });
            },

            pausePlay(player) {
                // console.log('player pause!', player)
                this.player.pause();
            },
            //显示编辑界面
            handleEdit: function (index, row) {
                this.editFormVisible = true;
                this.editForm = Object.assign({}, row);
                if (this.$refs.videoPlayer === undefined) {
                   this.playerOptions.sources[0]={
                    type: "video/mp4",
                    src: row.video
                    }
                }else {
                    let palyer = this.$refs.videoPlayer.player;
                    palyer.src(row.video);
                }

            },
            //显示新增界面
            cancleSubmit: function(){
                this.pausePlay();
                this.editFormVisible = false;
                this.editForm.visible=false;
            },
            //编辑
            editSubmit: function () {
                this.$refs.editForm.validate((valid) => {
                    if (valid) {
                        this.$confirm('确认提交吗？', '提示', {}).then(() => {
                            this.editLoading = true;
                            let para = Object.assign({}, this.editForm);
                            para.birth = (!para.birth || para.birth == '') ? '' : util.formatDate.format(new Date(para.birth), 'yyyy-MM-dd');
                            editUser(para).then((res) => {
                                this.editLoading = false;
                                this.$message({
                                    message: '提交成功',
                                    type: 'success'
                                });
                                this.$refs['editForm'].resetFields();
                                this.editFormVisible = false;
                                this.getVideoList();
                            });
                        });
                    }
                });
            },

            //批量删除
            batchRemove: function () {
                var ids = this.sels.map(item => item.userId).toString();
                this.$confirm('确认删除选中记录吗？', '提示', {
                    type: 'warning'
                }).then(() => {
                    this.listLoading = true;
                    let param = {userIds: ids};
                    console.log(ids);
                    batchRemoveUser(param).then((res) => {
                        this.listLoading = false;
                        if (res.status) {
                            this.$message({
                                message: '删除成功',
                                type: 'success'
                            });
                        } else {
                            this.$message({
                                message: '删除失败',
                                type: 'warning'
                            });
                        }
                        this.getVideoList();
                    });
                }).catch(() => {
                    this.listLoading = false;

                });
            }
        },
        computed: {
            player() {
                return this.$refs.videoPlayer.player
            }
        },

        created() {
            this.getVideoList()
        },
    }

</script>

<style scoped>
    .el-table .warning-row {
        background: oldlace;
    }
    .demo{
        display: inline-block;
        width: 90%;
        height: 90%;
        text-align: center;
        line-height: 100px;
        border: 1px solid transparent;
        border-radius: 4px;
        overflow: hidden;
        background: #fff;
        position: relative;
        box-shadow: 0 1px 1px rgba(0, 0, 0, .2);
        margin-right: 4px;
    }

    .demo:hover{
        display: block;
    }

    .el-table .success-row {
        background: #f0f9eb;
    }
    .video-js .vjs-big-play-button{

    }
</style>
